package com.thingsgrid.device.mapper;

import com.thingsgrid.device.dto.DeviceDTO;
import com.thingsgrid.device.entity.Device;
import com.thingsgrid.device.entity.DeviceMaintenanceRecord;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 功能说明：设备mapper
 *
 * @author 李龙飞
 * @since 2019/9/18 16:37
 */
@Repository("deviceMapper")
public class DeviceMapper {

	@Autowired
	private MongoTemplate mongoTemplate;

	/**
	 *说明：新增设备维护记录
	 *@author lilongfei
	 *@since 2019/9/5 19:55
	 */
	public void insertDeviceMaintenanceRecord(DeviceMaintenanceRecord deviceMaintenanceRecord){
		mongoTemplate.insert(deviceMaintenanceRecord,"device_maintenance_record");
	}

	/**
	 *说明：根据设备ID查询设备信息
	 *@author lilongfei
	 *@since 2019/9/18 16:53
	 */
	public Device getDeviceInfoById(String deviceId){
		return mongoTemplate.findById(deviceId,Device.class,"device");
	}

	/**
	 *说明：查询可关联的设备列表
	 *@author lilongfei
	 *@since 2019/9/26 15:07
	 */
	public List<DeviceDTO> getRelevanceDeviceList(Integer page, Integer size, String deviceId){
		Query query = new Query();
		Pageable pageable = new PageRequest(page - 1, size);
		query.with(pageable);
		query.addCriteria(Criteria.where("parent_device_id").is(null));
		query.addCriteria(Criteria.where("is_publish").is("1"));
		query.addCriteria(Criteria.where("device_id").not().in(deviceId));
		return mongoTemplate.find(query,DeviceDTO.class,"device");
	}

	/**
	 *说明：统计可关联设备数量
	 *@author lilongfei
	 *@since 2019/9/26 15:09
	 */
	public long getRelavanceDeviceCount(){
		Query query = new Query();
		query.addCriteria(Criteria.where("parent_device_id").is(null));
		query.addCriteria(Criteria.where("is_publish").is("1"));
		return mongoTemplate.count(query,Device.class,"device");
	}

	/**
	 *说明：通过产品id查询设备列表
	 *@author lilongfei
	 *@since 2019/9/27 14:24
	 */
	public List<Device> getDeviceListByProductId(String productId){
		Query query = new Query();
		query.addCriteria(Criteria.where("product_id").is(productId));
		return mongoTemplate.find(query,Device.class,"device");
	}

	/**
	 *说明：设备发布
	 *@author lilongfei
	 *@since 2019/9/29 14:20
	 */
	public long devicePublish(String deviceId,String publishState){
		Query query = new Query();
		query.addCriteria(Criteria.where("device_id").is(deviceId));
		Update update = new Update();
		update.set("is_publish",publishState);
		return mongoTemplate.updateFirst(query,update,"device").getModifiedCount();
	}


}
